package main

import (
	"fmt"
	"time"
)

/*
	请完成goroutine和channel协同工作的案例，要求如下：
	1、开启一个writeData协程，向管道intChan中写入50个整数
	2、开启一个readData协程，从管道intChan中读取writeData写入的数据
	3、writeData和readData操作的是同一个管道
	4、主线程需要等待writeData和readDData协程都完成工作后才能退出
*/

func main() {
	intChan := make(chan int, 50)
	exitChan := make(chan bool, 1)
	go writeData(intChan)
	go readData(intChan, exitChan)

	//for {
	//	_, ok := <-exitChan
	//	if !ok {
	//		break
	//	}
	//}
	<-exitChan
	fmt.Println("main ok")
}

func writeData(intChan chan int) {
	for i := 1; i < 50; i++ {
		intChan <- i
		time.Sleep(time.Second)
	}
	fmt.Println("write ok")
	close(intChan)
}

func readData(intChan chan int, exitChan chan bool) {
	for {
		v, ok := <-intChan
		time.Sleep(time.Second)
		if !ok {
			break
		}
		fmt.Printf("readData get data: %v\n", v)
	}
	fmt.Println("read ok")
	exitChan <- true
	close(exitChan)
}
